package com.mis.geoEncryption.model.data;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;

public class ResultGenerator implements IResultGenerator {
	
	private IItemExtractor itemExtractor;
	
	public ResultGenerator(IItemExtractor itemExtractor) {
		super();
		this.itemExtractor = itemExtractor;
	}
	
	private List getFinaleresult(List<Item> itemData) {
		String itemName = null;
		List finaleList = new ArrayList();
		Merchant merchant = new Merchant();
		for(Item item : itemData ) {
			if (itemName != null) {
				if (!itemName.equals(item.getMerchantName())) {
					itemName = item.getMerchantName();
					merchant.addItem(item);
					merchant.setMerchantName(itemName);
					finaleList.add(merchant);
				} else {
					merchant.addItem(item);
				}
			} else {
				itemName = item.getMerchantName();
				itemName = item.getMerchantName();
				merchant.addItem(item);
				merchant.setMerchantName(itemName);
			}
		}
		
		return finaleList;
	}
	
	private DealData prepareDealData(List merchantList) {
		DealData data = new DealData();
		data.setMerchantdata(merchantList);
		
		return data;
	}
	
	 private String convertToXML(Object source, Class type) {
        String result;
        StringWriter witer = new StringWriter();
        try {
            JAXBContext jxbContext = JAXBContext.newInstance(type);
            Marshaller jxbMarshaller = jxbContext.createMarshaller();
            jxbMarshaller.marshal(source, witer);
            result = witer.toString();
        } catch (JAXBException e) {
        	e.printStackTrace();
            throw new RuntimeException(e);
        }

        return result;
    }
	 
	 public String getXMLString() {
		 List<Item> itemData = itemExtractor.getItemData();
		 List<Item> newItemData = getFinaleresult(itemData);
		 DealData data = prepareDealData(newItemData);
		 String xmlString = convertToXML(data,DealData.class);
		 
		 return xmlString;
	 }
	 
}
